package ciicos.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ListUtil {

    public static boolean isEmpty(List list) {
        return list == null || list.size() == 0;
    }

    public static boolean isNotEmpty(List list) {
        return list != null && list.size() != 0;
    }

    public static <T, R> List<R> subList(List<T> entityList, Function<T, R> codeGetter) {
        if(isEmpty(entityList)){
            return new ArrayList<>();
        }
        return entityList.stream().map(codeGetter).collect(Collectors.toList());
    }

    public static List<String> parsefromString(String listStr) {
        List<String> idList = new ArrayList<>();
        try {
            List<String> type = JsonUtil.getJsonToList(listStr, String.class);
            if (type.size() > 0) {
                idList = type;
            }
        } catch (Exception e1) {
            try {
                String[] type = JsonUtil.getJsonToBean(listStr, String[].class);
                idList = Arrays.asList(type);
            } catch (Exception e2) {
                idList = new ArrayList<>();
                idList.add(String.valueOf(listStr));
            }
        }
        return idList;
    }

    public static <T, R> Map<R, List<T>> toMapList(List<T> entityList, Function<T, R> codeGetter, boolean defaultcode) {
        Map<R, List<T>> mapList = entityList.stream().collect(Collectors.groupingBy(codeGetter));
        if (defaultcode) {
            entityList.stream().forEach(
                    t -> {
                        mapList.computeIfAbsent(codeGetter.apply(t), k -> new ArrayList<>());
                    }
            );
        }
        return mapList;
    }

}
